package com.base.project

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.view.View
import android.widget.RelativeLayout
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import com.blankj.utilcode.util.LogUtils
import com.drake.brv.PageRefreshLayout
import com.drake.statelayout.StateConfig
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.hjq.toast.Toaster
import com.lxj.xpopup.XPopup
import com.orange.common.helper.UserHelper
import com.orange.common.ktx.loge
import com.scwang.smart.refresh.classics.ClassicsAbstract
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class App : Application(), ImageLoaderFactory {
    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        //brv
        initBrv()
        //XPopup
        initXPopup()
        //默认标题栏
        initTitleBar()
        //缺省页 全局配置
        initStateLayout()
        //toast
        Toaster.init(this)
        //日志
        LogUtils.getConfig().isLogSwitch = BuildConfig.DEBUG
        //mmkv
        MMKV.initialize(this)
        //获取adid
        getAdid()
        //初始化用户信息
        UserHelper.loadLocalUser()
    }

    /**
     * brv库相关初始化
     * 全局刷新样式
     * 分页索引初始值
     */
    private fun initBrv() {
        // 初始化BindingAdapter的默认绑定ID, 如果不使用DataBinding并不需要初始化
//        BRV.modelId = BR.m
        // 分页index初始值
        PageRefreshLayout.startIndex = 1
        // 刷新布局初始化
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
            MaterialHeader(context).apply {
                setColorSchemeColors(Color.parseColor("#96D128"))
            }
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            ClassicsFooter(context).apply {
                // 让加载提示居中
                val proView = findViewById<View>(ClassicsAbstract.ID_IMAGE_PROGRESS)
                val params = proView.layoutParams as RelativeLayout.LayoutParams
                params.removeRule(RelativeLayout.LEFT_OF)
                params.removeRule(RelativeLayout.START_OF)
                params.addRule(RelativeLayout.CENTER_IN_PARENT)
                proView.layoutParams = params
            }
        }

    }

    /**
     * XPopup 全局设置
     */
    private fun initXPopup() {
        XPopup.setShadowBgColor(Color.parseColor("#CC000000"))
    }

    /**
     * 默认标题栏样式
     */
    private fun initTitleBar() {
        // 初始化 TitleBar 默认样式
        //TitleBar.setDefaultStyle(LightBarStyle())
    }

    /**
     * 缺省页 全局配置 https://liangjingkanji.github.io/StateLayout/global/
     */
    private fun initStateLayout() {
        StateConfig.apply {
//            emptyLayout = R.layout.state_empty_layout // 配置全局的空布局
//            errorLayout = R.layout.state_error_layout // 配置全局的错误布局
//            loadingLayout = R.layout.state_loading_layout // 配置全局的加载中布局
//            setRetryIds(R.id.retry) // 全局的重试Id

            onError {
//                findViewById<TextView>(R.id.tvContent).text = TH.getString("app_no_network")
//                findViewById<TextView>(R.id.retry).text = TH.getString("app_refresh")
            }

            onEmpty {
//                findViewById<TextView>(R.id.tvTips).text = TH.getString("app_default_no_data")
            }
        }
    }

    /**
     * 获取adid
     */
    private fun getAdid() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val info = AdvertisingIdClient.getAdvertisingIdInfo(context)
                Constants.adId = info.id ?: ""
                loge("advertisingId-->${Constants.adId}")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun newImageLoader(): ImageLoader {
        return ImageLoader.Builder(this)
            .components {
                // gif支持
                if (Build.VERSION.SDK_INT >= 28) {
                    add(ImageDecoderDecoder.Factory())
                } else {
                    add(GifDecoder.Factory())
                }
            }
            .build()
    }
}